package edu.uestc.canary.commons;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    //对称加密中的公钥
    private static final String PUBLIC_KEY = "canary2024administrator07commons01admin";

    public static String compact(Map<String,?> payload){
        //生成 HMAC 密钥，根据提供的字节数组长度选择适当的 HMAC 算法，并返回相应的 SecretKey 对象。
        SecretKey key = Keys.hmacShaKeyFor(PUBLIC_KEY.getBytes(StandardCharsets.UTF_8));

        String jwt = Jwts.builder()
                .claims(payload)
                .signWith(key) //签名
                .compact();
        return jwt;
    }

    public static Map<String, ?> parse(String jwt){
        SecretKey key = Keys.hmacShaKeyFor(PUBLIC_KEY.getBytes(StandardCharsets.UTF_8));
        Jwt result = Jwts.parser().verifyWith(key).build().parse(jwt);
        Claims payload = (Claims) result.getPayload();
        //Header header = result.getHeader();

        return payload;
    }
}
